import React, { useRef, FC, forwardRef, useImperativeHandle, useState, useEffect } from 'react'
import { withRouter } from 'react-router-dom'
import TableDefined from '@/components/common/tableDefined'
import Dynamic from '@/api/dynamic'
import { modalLayoutSm } from '@/config/layout'
import { Button, Input, DatePicker, Select, Modal, Cascader,Spin, Upload, Table, Form, Steps, Row, Col, Tabs, Card, Radio, message, Checkbox } from 'antd';
import MyDefineSelect from '@/components/common/myDefineSelect'
import $axios from '@/utils/axios';
import { fn } from 'moment'
import TableDefinedEditCom from '@/components/common/tableDefinedEdit'
const {Option} = Select;
const delApiid = 'DMT_1003_3'
const searchApiId = 'DMT_1003';
const DataBase: FC = () => {
  const tableRef: RefType = useRef()
  const AddComRef: RefType = useRef()
  const [orderBy,setOrderBy] = useState('');
  const [loading,setLoading] = useState(true);
  const [connector,setconnector] = useState({});
  const [searchConfigList,setsearchConfigList] = useState([]);
  // 新增按钮
  const AddBtn = () => (
    <Button className="fr" onClick={add} type="primary">
      新增
    </Button>
  )
  // 添加
  const add = () => {
    AddComRef.current.init()
  }
   // 添加
  const edit = (id) => {
    AddComRef.current.init(id);
  }
  // 删除
  const del = (id:any) => {
    Modal.confirm({
      title: '确认删除？',
      
      onOk() {
        // Role.roleDel({
        //   roleid:record.roleid,
        //   isFormData:true
        // }).then(()=>{
        //   tableRef.current.update();
        // })
        Dynamic.DynamicExecute({
          apiID:delApiid,
          apiParam:{
            load_task_id:id
          }
        }).then((res)=>{
          tableRef.current.update();
        })
      },
      onCancel() {
      },
    });
  }
  const columns = [
      {
        title: '操作',
        align: 'left',
        dataIndex: 'scan',
        key: 'scan',
        width: '180px',
        fixed: 'right',
        render: (text, record, index) => {
          return <div>
          <Button className="btn" onClick={()=>edit(record.load_task_id)} size="small">编辑</Button>
          {/* {
             record.status=='2'&&<Button style={{marginLeft:'10px'}} className="btn" onClick={()=>start(record.tran_task_id)} size="small">启动</Button>
          } */}
          <Button style={{marginLeft:'10px'}} className="btn" onClick={()=>del(record.load_task_id)} size="small">删除</Button>
        </div>
        }
      }
] 
  const getSearchConfig = ()=>{
    Dynamic.getDynamicQuery({
      apiID:'DMT_MNG_01',
      apiParam:{
          api_id:searchApiId
      }
    }).then((res)=>{
      let data = res.data;
      let apiParamStr = data.data['0']['api_param']?data.data['0']['api_param']:'';
      let  apiParam= data.data['0']['api_param']?JSON.parse(data.data['0']['api_param']):{};
      let {paramList = []} = apiParam;
      paramList.map((e,i)=>{

        switch(e.name){
          case "where"://查询条件
            let element = e.element||[];
            let searchConfigListNew = [];

            let connectorNew = {};
            
            element.map((el,il)=>{
              connectorNew[el.feild] = el['connector'];
              let ele =  {
                "key": el.feild,
                // "slot": <Input placeholder={"请输入"+el.label} allowClear />,
                "rules": [],
                // "initialValue": '',
                "label":el.label,
              }
              switch(el.type){
                case 'text':
                  ele['slot'] = <Input placeholder={"请输入"+el.label} allowClear />;
                  break;
                case 'checkbox':
                  ele['slot'] = <Checkbox.Group style={{maxWidth:window.innerWidth/2-100+'px'}}>
                    {
                        el.option.map((ek,ik)=>{
                          return <Checkbox defaultChecked={ek.checked} key={ik} value={ek.value}>{ek.label}</Checkbox>
                        })
                    }
                  </Checkbox.Group>
                  break;
                case 'select':
                  if(el.mode=="multiple"){
                    ele['slot'] = <Select allowClear mode='multiple' placeholder={'请选择'+el.label} style={{maxWidth:window.innerWidth/2-100+'px',minWidth:'120px'}}>
                    {
                        el.option.map((ek,ik)=>{
                          return <Option defaultChecked={ek.checked} key={ik} value={ek.value}>{ek.label}</Option>
                        })
                    }
                  </Select>
                  }else{
                    ele['slot'] = <Select allowClear placeholder={'请选择'+el.label} style={{maxWidth:window.innerWidth/2-100+'px',minWidth:'120px'}}>
                    {
                        el.option.map((ek,ik)=>{
                          return <Option defaultChecked={ek.checked} key={ik} value={ek.value}>{ek.label}</Option>
                        })
                    }
                  </Select>
                  }
                 
                default:
                  break;
              }
              searchConfigListNew.push(ele)
              setconnector(connectorNew)
            })
            setsearchConfigList(searchConfigListNew);
           
            break;
          case 'orderBy'://排序
            setOrderBy(e.value);
            break;
          case 'paging'://分页
            break;
        }
      })

      setLoading(false);
    })
    
  }
  useEffect(()=>{
    getSearchConfig();
  },[])
  return (
    <>
      <div >
        {/* <BatchDel /> */}
        <AddBtn />
      </div>
      <div>
      {
        !loading&&<TableDefined
        apiFun={Dynamic.getDynamicQuery}
        columns={columns}
        ref={tableRef}
        searchConfigList={searchConfigList}
        // search_tran_name
        extraProps={{ apiID: 'DMT_1003',apiParam:{'orderBy':orderBy}}}
        beforeSearch={(val: any) => {
          // eslint-disable-next-line no-param-reassign
          val.where = [];
          for(let i in val){
            if(i!='where'&&val[i]&&val[i]['length']>0){
              val.where.push({"feild":i, "connector":connector[i], "value":val[i]})
            }
          }
          for(let i in val){
            if(i!='where'){
              delete val[i];
            }
          }
          
          // eslint-disable-next-line no-param-reassign
          return {}
        }} 
      />
      }
      
       <TableDefinedEditCom ref={AddComRef} 
        apiID="DMT_MNG_01"
        apiParamMng_id = "DMT_1003_1"
        addApiId = 'DMT_1003_1'
        updateApiId = 'DMT_1003_2'
        detailApiId = 'DMT_1003_7'
        callback={() => {
        tableRef.current.update();
      }} />
      </div>
    </>
  )
}
export default withRouter(DataBase)

















